<template>
  <el-dialog title="批量修改收件地址" v-model="visible" align-center width="90%" @close="handleClose" :close-on-click-modal="false" :append-to-body="true">
    <div class="flex">
      <div class="flex-1">说明：只允许订单状态为<span class="text-red">问题订单、已确认</span>的订单进行批量修改地址</div>
      <div><el-button type="primary" @click="batchCity">批量填充省市</el-button></div>
    </div>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #batchHeader="{ column }">
        <span class="title">
          {{ column.title }}
          <el-button type="primary" size="small" class="ml-[4px]" @click="batchOpen(column)">批量</el-button>
        </span>
      </template>
      <template #Country="{ row }">
        <VSelect v-model="row.recipient_country" clearable class="w-[100%]" confusedPaste :paste="true" :options="countryOpt" />
      </template>
      <template #CountryName="{ row }">
        {{ countryOpt.find((v) => v.value == row.recipient_country)?.label }}
      </template>
    </VTable>

    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="save">确认</el-button>
    </template>
  </el-dialog>

  <!-- 批量修改弹窗 -->
  <el-dialog :title="batchConfig.title" v-model="batchConfig.visible" align-center width="520" @close="batchClose" :close-on-click-modal="false" :append-to-body="true">
    <el-form>
      <el-form-item :label="batchConfig.item.title">
        <el-input v-model="batchConfig.value" :placeholder="batchConfig.item.title" class="w-[90%]" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="batchClose">关闭</el-button>
      <el-button type="primary" @click="batchSave">确认</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="jsx">
const emit = defineEmits(["submit"])
import { ElMessage } from "element-plus"

const batchCity = () => {
  let data = tableData.value
  data.forEach((item) => {
    item.recipient_province = item.recipient_province || item.recipient_city
    item.recipient_city = item.recipient_city || item.recipient_province
  })
  tableRef.value.$table.loadData(data)
  tableData.value = data
}
const tableRef = ref()
// 批量修改
const batchConfig = ref({ visible: false, title: "", item: {}, value: "" })
const batchSave = () => {
  if (batchConfig.value.value) {
    let data = tableData.value
    data = data?.map((v) => ({ ...v, [batchConfig.value.item.field]: batchConfig.value.value }))
    tableRef.value.$table.loadData(data)
    tableData.value = data
    batchClose()
  } else {
    ElMessage({ showClose: true, message: "请输入数据！", type: "warning" })
  }
}
const batchClose = () => {
  batchConfig.value.visible = false
  batchConfig.value.value = ""
}
const batchOpen = (item) => {
  batchConfig.value.title = `批量修改${item.title}`
  batchConfig.value.item = item
  batchConfig.value.visible = true
}
const tableOptins = reactive({
  height: "600",
  keepSource: true,
  editConfig: { trigger: "click", mode: "cell", showStatus: true },
  editRules: {
    recipient_name: [{ required: true, message: "请输入" }],
    recipient_last_name: [{ required: true, message: "请输入" }],
    recipient_phone: [{ required: true, message: "请输入" }],
    recipient_country: [{ required: true, message: "请输入" }],
    // recipient_region: [{ required: true, message: "请输入" }],
    recipient_zip_code: [{ required: true, message: "请输入" }],
    recipient_preferred_address: [{ required: true, message: "请输入" }],
  },

  columns: [
    { field: "order_sn", title: "系统订单号", width: 150 },
    { field: "order_status_desc", title: "订单状态", width: 120 },

    { field: "recipient_name", title: "收件人名", width: 140, editRender: { name: "input" } },
    { field: "recipient_last_name", title: "收件人姓", width: 140, editRender: { name: "input" } },
    { field: "sender_tax_no", title: "寄件人税号", width: 160, editRender: { name: "input" }, slots: { header: "batchHeader" } },
    { field: "recipient_phone", title: "联系电话", width: 160, editRender: { name: "input" }, slots: { header: "batchHeader" } },
    { field: "recipient_email", title: "邮箱", width: 140, editRender: { name: "input" }, slots: { header: "batchHeader" } },

    { field: "recipient_country", title: "国家", width: 140, editRender: { props: { placeholder: "请选择" } }, slots: { edit: "Country", default: "CountryName" } },

    { field: "recipient_province", title: "州、省", width: 140, editRender: { name: "input" }, slots: { header: "batchHeader" } },
    { field: "recipient_city", title: "城市", width: 140, editRender: { name: "input" }, slots: { header: "batchHeader" } },
    { field: "recipient_region", title: "区县", width: 140, editRender: { name: "input" } },
    { field: "recipient_zip_code", title: "邮编", width: 140, editRender: { name: "input" } },
    { field: "recipient_preferred_address", title: "详细地址1", width: 300, editRender: { name: "input" } },
    { field: "recipient_secondary_address", title: "详细地址2", width: 300, editRender: { name: "input" } },
    { field: "recipient_door_num", title: "门牌号", width: 140, editRender: { name: "input" } },
    {
      title: "操作",
      width: 100,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }) => (
          <el-button link type="danger" onClick={() => delRow(rowIndex)}>
            删除
          </el-button>
        ),
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async () => {
        return []
      },
    },
  },
})
const delRow = (rowIndex) => {
  let data = tableData.value
  data.splice(rowIndex, 1)
  tableRef.value.$table.loadData(data)
  tableData.value = data
}

const save = async () => {
  let errMap = await tableRef.value.$table.validate()
  if (errMap) {
    ElMessage({ showClose: true, message: "必填项不能为空，请检查！", type: "warning" })
  } else {
    emit("submit", { input: tableData.value })
    nextTick(() => handleClose())
  }
}
const tableData = ref([])
const visible = ref(false)
// 打开弹窗
const open = async (rows) => {
  visible.value = true
  let data = rows?.map((v) => ({ ...v.recipient, order_sn: v.order_sn, order_status_desc: v.order_status_desc }))
  tableData.value = JSON.parse(JSON.stringify(data))
  setTimeout(() => {
    nextTick(() => {
      tableRef.value.$table.loadData(tableData.value)
      getCountry()
    })
  }, 100)
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  tableData.value = []
}

// 获取站点
import { getCountryOption } from "@/api/public.js"
import { nextTick } from "vue"
const countryOpt = ref([])
const getCountry = async () => {
  try {
    const { data } = await getCountryOption()
    countryOpt.value = data.map((v) => ({
      label: `${v.name} ${v.country}`,
      value: v.country,
      id: v.id,
    }))
  } catch (e) {
    console.error(e)
  }
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped></style>
